package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @Author da
 * @Date 2021/8/15 下午 1:59
 */
@RestController
@RequestMapping("/user")
public class UserController
{
    @Resource
    UserMapper userMapper;

    //    用户登陆
    @PostMapping("/login")
    public Result<?> login(@RequestBody User user)
    {
//        查询数据库中用户的数据
        User one = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()).eq(User::getPassword, user.getPassword()));
        if (one == null)
        {
            return Result.error("-1", "用户名或者密码错误");
        }
        return Result.success(one);
    }

    //    用户注册
    @PostMapping("/register")
    public Result<?> register(@RequestBody User user)
    {
//        查询数据库中用户的数据,判断用户是否已经存在
        User one = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
        if (one != null)
        {
            return Result.error("-1", "改用户名已存在,不能注册");
        }
//        如果密码为空设置默认密码为123456
        if (user.getPassword() == null)
        {
            user.setPassword("123456");
        }
//        插入数据
        userMapper.insert(user);
        return Result.success();
    }


    //    插入用户
    @PostMapping
    public Result<?> save(@RequestBody User user)
    {
//        设置默认密码
        if (user.getPassword() == null)
        {
            user.setPassword("123456");
        }
        userMapper.insert(user);
        return Result.success();
    }

    //    更新用户
    @PutMapping
    public Result<?> update(@RequestBody User user)
    {
        userMapper.updateById(user);
        return Result.success();
    }

    //    删除用户
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id)
    {
        userMapper.deleteById(id);
        return Result.success();
    }

    //    分页查询
    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search)
    {
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery();
//        search不为空才模糊查询
        if (StrUtil.isNotBlank(search))
        {
            wrapper.like(User::getNickName, search);
        }
        Page<User> userPage = userMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(userPage);
    }
}
